package com.yuanyi.controller;



import com.yuanyi.util.OSSUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;

import java.util.UUID;

@RestController
public class OSSController {
    //OSS 图片
    @PostMapping("/ossupload")
    public String ossupload(String base64) throws IOException {
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] b = decoder.decodeBuffer(base64);

        String pName = UUID.randomUUID().toString();
        ByteArrayInputStream bis = new ByteArrayInputStream(b);
        Thumbnails.Builder<? extends InputStream> builder = Thumbnails.of(bis).size(100, 150);
        try {
            BufferedImage bufferedImage = builder.asBufferedImage();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "png", baos);
            byte[] byteArray = baos.toByteArray();
            OSSUtil.ossUpload(pName+".jpg_s.jpg",byteArray);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        OSSUtil.ossUpload(pName+".jpg",b);
        return pName+".jpg";
    }

    //http://localhost/ossdownload?pName=bf41bc5e-a153-4d7a-8d06-3ee4abbecdac.jpg
    @GetMapping(value = "/ossdownload")
    public void ossdownload(String pName,HttpServletResponse response) throws IOException {
        // return OSSUtil.ossDownload(pName);
        response.setHeader("Content-type","image/jpeg");

        OSSUtil.ossDownload(response,pName);


    }
}
